import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Table } from 'semantic-ui-react'
import Styled from 'styled-components'
import { BasicButton, PrimaryButton } from 'components/Button'
import { validForm as validFormDuck } from 'ducks'
import SwitchButtons from './multiSwitchButton'
import QueryField from './queryField'

const SectionRow = Styled.div`
  margin-bottom: 1em;
`
class SwitchButtonsView extends Component {
  componentDidMount() {
    const {
      options, actionInitField, name, required, initValues
    } = this.props
    actionInitField({
      name,
      value: options.reduce((pre, next, i) => {
        pre[next.name] = initValues ? initValues[i] : false
        return pre
      }, {}),
      state: 'success',
      required,
    })
  }

  render() {
    const {
      header, description, options, submit, field, name,
    } = this.props
    return (
      <Table.Row>
        <Table.Cell width="4" verticalAlign="top">
          {header}
        </Table.Cell>
        <Table.Cell>
          <SectionRow>{description}</SectionRow>
          <SectionRow>{field && <SwitchButtons name={name} ops={options} />}</SectionRow>
          {submit && (
            <SectionRow>
              <BasicButton content="取消" />
              <PrimaryButton content="保存" primary />
            </SectionRow>
          )}
        </Table.Cell>
      </Table.Row>
    )
  }
}

const mapStateToProps = (state, ownProps) => ({
  field: validFormDuck.selectors.field(state, ownProps.name),
})

const mapDispatchToProps = {
  actionInitField: validFormDuck.creators.actionInitField,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(QueryField(SwitchButtonsView, options => ({ options })))
